# encoding: utf-8

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api import memcache
import models
import logging
import options
import datetime
from models import taggable

def init_blog():
    """Set the default content of the blog"""
    link = models.Link(name="Google App Engine",link="http://code.google.com/appengine/")
    link.put()
    link1 = models.Link(name="GAE group", link="http://groups.google.com/group/google-appengine")
    link1.put()
    link2 = models.Link(name="Friend", link="http://woiclub.appspot.com")
    link2.put()
#    host=self.request.host_url
    host=options.BLOGSITES
    feed = models.Feed(link_autor='''http://img.feedsky.com/images/icon_subshot01_zhuaxia.gif''', link="http://www.zhuaxia.com/add_channel.php?url="+host,link_alt="&#25235;&#34430;")
    feed.put()
    feed = models.Feed(link_autor='''http://img.feedsky.com/images/icon_subshot01_pageflakes.gif''', link="http://www.pageflakes.com/subscribe.aspx?url="+host,link_alt="pageflakes")
    feed.put()
    feed = models.Feed(link_autor='''http://img.feedsky.com/images/icon_subshot01_google.gif''', link="http://fusion.google.com/add?feedurl="+host,link_alt="google reader",order=0)
    feed.put()
    feed = models.Feed(link_autor='''http://img.feedsky.com/images/icon_subshot01_bloglines.gif''', link="http://www.bloglines.com/sub/"+host,link_alt="bloglines")
    feed.put()
    feed = models.Feed(link_autor='''http://img.feedsky.com/images/icon_subshot01_xianguo.gif''', link="http://www.xianguo.com/subscribe.php?url="+host,link_alt="&#40092;&#26524;")
    feed.put()
    feed = models.Feed(link_autor='''http://img.feedsky.com/images/icon_subshot01_nazha.gif''', link="http://inezha.com/add?url="+host,link_alt="&#21738;&#21522;")
    feed.put()
    feed = models.Feed(link_autor='''http://img.feedsky.com/images/icon_subshot01_youdao.gif''', link="http://reader.yodao.com/#url="+host,link_alt="&#26377;&#36947;")
    feed.put()
    
    category = models.Category(key_name="cat_a_category", 
                             category_name="A category", 
                             category_url="a_category")
    category.put()
    post = models.Post(key_name= 'post_hello_world',
                       title="Hello world!",
                       content="This is a sample post",
                       permalink="hello_world",
                       published=datetime.datetime.now(),
                       categories_keys = [category.key()],
                       draft=False,
                       creator=users.User("yuping322@gmail.com")
                       )
    post.put()
    des = post.modified.strftime('%Y-%m')
    archive = models.Archive.all().filter('yearmonth',des).fetch(10)
        # add to archive
    if archive == []: # new month
        archive = models.Archive(yearmonth=des)
    else: 
        archive = archive[0]
    archive.entrycount += 1
    archive.put()
    
def navigation(offset, total_count, limit=10):
    if offset:
      try:
        offset = int(offset)
      except:
        offset = 1
      else:
        offset = max(1, offset)
    else:
      offset = 1
    if offset>1:
        previous_list = range(1,offset)
        previous = offset -1
    else:
        previous_list = None
        previous = None
    last=((total_count-1)/limit)+1
    if last>offset:
        next_list = range(offset+1,last+1)
        next = offset + 1
    else:
        next_list = None
        next = None
    response = {'previous_list' : previous_list,
                'previous':previous,
                'current': offset,
                'next': next,
                'next_list': next_list,
                'last': last }
    return response

#def do_categories():
#    cats = models.Category.all().order('category_name')
#    str = u''
#    if cats.count():
#        str = u"<div><h3>分类</h3>\n<ul>"
#        for cat in cats:
#            str += '<li><a href="/category/' + cat.category_url + '">' + cat.category_name + '</a></li>\n'
#        str += "</ul></div>\n"
#    return str
#
#
#def do_archives():
#    arcs = models.Archive.all().order('yearmonth')
#    str = u''
#    if arcs.count():
#        str = u"<div><h3>日期</h3>\n<ul>"
#        for arc in arcs:
#            str += '<li><a href="/archive/' + arc.yearmonth + '">' + arc.yearmonth +'(' + unicode(arc.entrycount) + ')</a></li>\n'
#        str += "</ul></div>\n"
#    return str
#
#def do_tags():
#    tags = taggable.Tag.Get_Tags_By_Frequency()[:10]
#    str = u''
#    if len(tags):
#        str = u"<div><h3>标签</h3>\n<ul>"
##        str +='<p id="tagsCloud">'
#        for tag in tags:
##            from __future__ import divisions
##            fontSize=9+len(tag.tagged)
##            if fontSize>20:
##                fontSize=20
#            fontSize=10
#            str +='<li><a href="/tag/' + tag.tag + '"; style="font-size:'+unicode(fontSize)+'pt;">'+ tag.tag +'</a></li>\n'
##            str += '<li><a href="/tag/' + tag.tag + '">' + tag.tag +'(' + unicode(len(tag.tagged)) + ')</a></li>\n'
#        str += "</ul></div>\n"
#    return str
#
##Pages
#def do_pages():
#    pages = models.Post.all().filter('post_type', 'page').order('title')
#    str = u''
#    if pages.count():
#        str += u"<div><h3>页面</h3>\n<ul>"
#        for page in pages:
#            str += '<li><a href="/page/' + page.permalink + '">' + page.title + '</a></li>\n'
#        str += "</ul></div>\n"
#    return str
#
##links
#def do_links():
#    links = models.Link.all()
#    str = u''
#    if links.count():
#        str += u"<div><h3>链接</h3>\n<ul>"
#        for link in links:
#            str += '<li><a href="' + link.link + '">' + link.name + '</a></li>\n'
#        str += "</ul></div>\n"
#    return str
#
##links
#def do_recentcomments():
#    comments = models.Comment.all().order('-date')
#    str = u''
#    if comments.count():
#        str += u"<div><h3>最新评论</h3>\n<ul>"
#        for comment in comments:
#            cmt =comment.text
#            if len(cmt)>50:
#                cmt=cmt[:50]+"......"
#            str += '<li>'+comment.author+':<a href="/post/' + comment.post.permalink + '">' + cmt + '</a></li>\n'
#        str += "</ul></div>\n"
#    return str
#  
##feed
#def do_feed():
##        return '<div><a href="/feed"><img src="/static/images/feed.png"></a></div>'
#    return u"""<div><h3>订阅
#                <a href="/feed"><img src="/static/images/feed.png"></a></h3>
#                <br/>
#                <a href="http://www.zhuaxia.com/add_channel.php?url=http://www.woiclub.cn/feed"><img border="0" src="http://img.feedsky.com/images/icon_subshot01_zhuaxia.gif" alt="&#25235;&#34430;" vspace="2" style="margin-bottom:3px"></a>
#                <br/>
#                <a href="http://www.pageflakes.com/subscribe.aspx?url=http://www.woiclub.cn/feed"><img border="0" src="http://img.feedsky.com/images/icon_subshot01_pageflakes.gif" alt="pageflakes" vspace="2" style="margin-bottom:3px"></a>
#                <br/>
#                <a href="http://fusion.google.com/add?feedurl=http://www.woiclub.cn/feed"><img border="0" src="http://img.feedsky.com/images/icon_subshot01_google.gif" alt="google reader" vspace="2" style="margin-bottom:3px"></a>
#                <br/>
#                <a href="http://www.bloglines.com/sub/http://www.woiclub.cn/feed"><img border="0" src="http://img.feedsky.com/images/icon_subshot01_bloglines.gif" alt="bloglines" vspace="2" style="margin-bottom:3px"></a>
#                <br/>
#                <a href="http://www.xianguo.com/subscribe.php?url=http://www.woiclub.cn/feed"><img border="0" src="http://img.feedsky.com/images/icon_subshot01_xianguo.gif" alt="&#40092;&#26524;" vspace="2" style="margin-bottom:3px"></a>
#                <br/>
#                <a href="http://inezha.com/add?url=http://www.woiclub.cn/feed"><img border="0" src="http://img.feedsky.com/images/icon_subshot01_nazha.gif" alt="&#21738;&#21522;" vspace="2" style="margin-bottom:3px"></a>
#                <br/>
#                <a href="http://reader.yodao.com/#url=http://www.woiclub.cn/feed"><img border="0" src="http://img.feedsky.com/images/icon_subshot01_youdao.gif" alt="&#26377;&#36947;" vspace="2" style="margin-bottom:3px"></a>
#                <br/>
#             </div>"""
#
##widgets
#def do_widget(key):
#    str = u''
#    try:
#        widget = models.SidebarWidget.get(db.Key(key))
#    except db.Error:
#        return str
#    if widget is not None:
#        str += '<div>'
#        if widget.title:
#            str += '<h3>' + widget.title + '</h3>'
#        return str + widget.text + '</div>'    
#        
#def do_sidebar():  
#    sidebar = u''
#    constructors = {}
#    #Categories
#    constructors['categories'] = do_categories
#    constructors['archives'] = do_archives
#    constructors['tags'] = do_tags
#    constructors['pages'] = do_pages
#    constructors['links'] = do_links 
#    constructors['feed'] = do_feed
#    constructors['recentcomments'] = do_recentcomments
#    options = get_options()
#    opt = options.sidebar_widgets
#    for item in opt:
#        if item in ("categories" , "pages", "links", "feed","archives","tags","recentcomments"):
#            sidebar += constructors[item]()
#        else:
#            sidebar += do_widget(item)
#    return sidebar
#
#def get_sidebar():
#    """get_sidebar()
#
#    Checks the cache to see if there are cached sidebar.
#    If not, call render_greetings and set the cache
#
#    Returns:
#    A string of HTML containing sidebar.
#    """
#    try:
#        sidebar = memcache.get("sidebar")
#    except:
#        sidebar = None
#    if sidebar is not None:
#        logging.info('Memcache get succefull, sidebar retrived')
#        return sidebar
#    else:
#        memcache.flush_all()
#        sidebar = do_sidebar()
#        che = str(get_options().sidebar_widgets)
#        if not memcache.add("sidebar", sidebar):
#            logging.info('Memcache set failed. Trying to cache sidebar:%s' % che)
#        else:
#            logging.info('Memcache set succefull. Trying to cache sidebar:%s' % che)
#        return sidebar
        

def get_options():
    """get_options()

    Checks the cache to see if there are cached sidebar.
    If not, call render_greetings and set the cache

    Returns:
    A string of HTML containing sidebar.
    """
    #memcache.delete("options")
    #print 'getting'
    try:
        opts = memcache.get("options")
    except:
        opts = None
    if opts is not None:
        logging.info('Memcache get succefull, options retrived')
        return opts
    else:
        opts = options.Options()
        if not memcache.add("options", opts):
            logging.info('Memcache set failed. Trying to cache opts:%s' % opts)
            #logging.info('Memcache set failed. Memcache stats:%s' % memcache.get_stats() )
        else:
            logging.info('Memcache set succefull. Trying to cache opts:%s' % opts)
        return opts

def w_categories():
    cats = models.Category.all().order('category_name')
    return ["categories",cats]


def w_archives():
    arcs = models.Archive.all().order('yearmonth')
    return ["archives",arcs]

def w_tags():
    tags = taggable.Tag.Get_Tags_By_Frequency()
    return ["tags",tags]

#Pages
def w_pages():
    pages = models.Post.all().filter('post_type', 'page').order('title')
    return ["pages",pages]

#links
def w_links():
    links = models.Link.all()
    return ["links",links]

#links
def w_recentcomments():
    comments = models.Comment.all().order('-date')
    str =[]
    for comment in comments:
        cmt =comment.text
        if len(cmt)>50:
            cmt=cmt[:50]+"......"
        str.append({'author':comment.author,'permalink':comment.post.permalink,'text':cmt})
    return ["recentcomments",str]
  
#feed
def w_feed():
#        return '<div><a href="/feed"><img src="/static/images/feed.png"></a></div>'
    feeds=models.Feed.all().order('order')
    return ["feed",feeds]

#widgets
def w_widget(key):
    widget = {}
    try:
        widget = models.SidebarWidget.get(db.Key(key))
#        widget.update({"title":widgetm.title,"text":widgetm.text})
    except db.Error:
        return widget
    if widget is not None:
        return widget

def w_sidebar():
    """get_sidebar()

    Checks the cache to see if there are cached sidebar.
    If not, call render_greetings and set the cache

    Returns:
    A string of HTML containing sidebar.
    """
    try:
        sidebar = memcache.get("sidebardata")
    except:
        sidebar = None
    if sidebar is not None:
        logging.info('Memcache get succefull, sidebar retrived')
        return sidebar
    else:
        memcache.flush_all()
        
        sidebar = []
        constructors = {}
        constructors['categories'] = w_categories
        constructors['archives'] = w_archives
        constructors['tags'] = w_tags
        constructors['pages'] = w_pages
        constructors['links'] = w_links 
        constructors['feed'] = w_feed
        constructors['recentcomments'] = w_recentcomments
        options = get_options()
        opt = options.sidebar_widgets
        for item in opt:
            if item in ("categories" , "pages", "links", "feed","archives","tags","recentcomments"):
                sidebar.append(constructors[item]())
            else:
                w=[]
                w.append("widget")
                w.append(w_widget(item))
                sidebar.append(w)
                
        try:
            memcache.add("sidebardata", sidebar)
        except:
            pass
        return sidebar
"""#functions.safeget(options=options,key='abc',default='')"""
def safeget(options,key,default):
    a=''
    try:
        a=options.__getattribute__(key)
    except:
        a=default
    return a

def format_date(dt):
    return dt.strftime('%a, %d %b %Y %H:%M:%S GMT')